//
//  ConsultingDoctorViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/2/14.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ConsultingDoctorViewController.h"
#import "PointOutView.h"
#import "ZUnpaidView.h" // 未支付的View
#import "ZPublishDetailsViewController.h"
#import "LZSectedPicVC.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "JTAlertView.h"
#import "JNavigationController.h"
#import "LZLoginViewController.h"
#import "SPVoiceManager.h"
#import <AVFoundation/AVFoundation.h>
#import "JTTakeAlbumOrCamera.h"
static NSInteger  const ButtonTag = 200; // 按钮的tag值


@interface ConsultingDoctorViewController ()<ZJQPointOutDelegate,UITextViewDelegate,UIImagePickerControllerDelegate,AVAudioRecorderDelegate>
{
    LZUserInfo *userInfo;
    
    // 病情描述
    UILabel * _describeLabel;
    UITextView * _describeTextView;
    UILabel * _placeholderLabel;
    //听语音
    UILabel * _voicelable;
    UIButton * _voiceBtn;
    // 图片部分
    UILabel * _consultLabel;
    UIButton * _imageBtn1;
    UIButton * _imageBtn2;
    UIButton * _imageBtn3;
    UILabel * _imageLabel1;
    UILabel * _imageLabel2;
    UILabel * _imageLabel3;
    //发布语音
    UIButton * _postVoiceBtn;
    NSUInteger  _selectIndex ;// 记录被选中的是哪一个按钮;
    
    NSString *urlPlay;
    NSURL    *_recordUrl;
    //录音机
    AVAudioSession *_audioSession;
    AVAudioRecorder *recorder;
    //定时器
    NSTimer *_timer;
    //中间的显示话筒的视图
    UIView     *_callView;
    //话筒
    UIImageView *_imgView;
    //显示音阶
    UIImageView *_yinjieBtn;
    //显示文字，这里设置为空即可
    UILabel     *_label;
    UIView      *_maskView;
    
    UIButton *  _rightBarBtn;
    
    NSLayoutConstraint *_maskH;
    NSLayoutConstraint *_centerX;
    NSMutableDictionary * _imageDict;// 存图片的dict
}
@property (nonatomic,strong) UIScrollView * mainScrollView;
@property (nonatomic,strong) PointOutView * pointOutView;
@property (nonatomic,strong) ZUnpaidView * unpaidView;

//@property (nonatomic,strong)UIImageView * recordVoice;
@property (nonatomic,strong) UILabel * recordDuraTimeLabel;
/** 播放器 **/
@property (nonatomic,strong) AVAudioPlayer * avPlay;
/** 记录录音时长 **/
@property (nonatomic,assign) int time_number;
/** 上传的录音时长 **/
@property (nonatomic,strong) NSString * postTimeNumber;

/** 记录是否发布语音 **/
@property (nonatomic,assign) BOOL voice;
//跳转需要的字典
@property (nonatomic,strong) NSMutableDictionary * jumpDict;
@end

@implementation ConsultingDoctorViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if ([[SPVoiceManager defaultManager] isPlaying]) {
        [[SPVoiceManager defaultManager] stop];
    }
}


    

- (void)viewDidLoad {
    [super viewDidLoad];
    userInfo = [LZUserInfo getUserInfo];
    [self initialzeDatas];
    [self initlizeInterface];
    [self addLongPressGesture];
    [self setUpRecord];
    
    // 选中照片传回来的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(returnPicNoc:) name:@"returnMaxPic" object:nil];
}


// 返回选择的照片
- (void)returnPicNoc:(NSNotification *)sender {
    LZLog(@"----ss--%@",sender);
    NSDictionary *dic = sender.userInfo;
    if ([sender.userInfo[@"selecIndex"] integerValue]== 1) {
        [_imageBtn1 sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"img_max"]] forState:UIControlStateNormal];
        
        // 拿到照片1
        NSString *tempStr = dic[@"img_max"];
        NSArray * array = [tempStr componentsSeparatedByString:IconURL];
        [_jumpDict setObject:[array lastObject] forKey:@"part"];
        
    }else if ([sender.userInfo[@"selecIndex"] integerValue] == 2) {
        [_imageBtn2 sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"img_max"]] forState:UIControlStateNormal];
        // 拿到照片2
        NSString *tempStr = dic[@"img_max"];
        NSArray * array = [tempStr componentsSeparatedByString:IconURL];
        [_jumpDict setObject:[array lastObject] forKey:@"report"];
        
    }else {
        [_imageBtn3 sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"img_max"]] forState:UIControlStateNormal];
        // 拿到照片3
        NSString *tempStr = dic[@"img_max"];
        NSArray * array = [tempStr componentsSeparatedByString:IconURL];
        [_jumpDict setObject:[array lastObject] forKey:@"xray"];
        
    }
}

// 移除通知中心
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //移除录音
    NSString *name = [NSString stringWithFormat:@"/data.aac"];
    //沙盒路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:name];
    
    
    NSFileManager* fileManager=[NSFileManager defaultManager];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:path];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@"患者 have");
        BOOL blDele= [fileManager removeItemAtPath:path error:nil];
        if (blDele) {
            NSLog(@"患者 dele success");
        }else {
            NSLog(@"dele fail");
        }
        
    }

}

- (void)initialzeDatas {
    _imageDict = [@{} mutableCopy];
    _jumpDict = [@{} mutableCopy];
    _recordUrl = nil;
    _voice = NO;
    _postTimeNumber = @"";
}

- (void)initlizeInterface {
    self.navigationItem.title = @"咨询医生";
    self.view.backgroundColor = MYGRAYCOLOR;
    [self makerightButton];
    [self makeTheSubView];
    [self addSubViewAndMasony];
}




// 设置右边的发布
- (void)makerightButton {
        _rightBarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBarBtn setTitle:@"发布" forState:UIControlStateNormal];
    [_rightBarBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    _rightBarBtn.frame = CGRectMake(0, 0, 40, 30);
    [_rightBarBtn addTarget:self action:@selector(concrightBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightButonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBarBtn];
    self.navigationItem.rightBarButtonItem = rightButonItem;
}


- (void)concrightBtnAction {
    _rightBarBtn.userInteractionEnabled = NO;
    // 先判断 文本和录音是否同时为空
    if ([_describeTextView.text isEqualToString:@""]&& !_voice) {
            _rightBarBtn.userInteractionEnabled = YES;
            [YJProgressHUD showMessage:@"描述和语音不能同时为空" inView:self.view];
            return;
    }
    // 图片和录音都不存在 只存在文本
    if(_imageDict.allKeys.count == 0 && !_voice) {
       _rightBarBtn.userInteractionEnabled = YES;
        [self jumpdetailVCWith:[@{} mutableCopy]];
    }else {
    // 上传图片或者录音
        [self UploadImageAndVoice];
    }
}
// 创建视图
- (void)makeTheSubView{
    // 描述部分
    _describeLabel  = [[UILabel alloc] init];
    [self setThelabel:_describeLabel color:[UIColor blackColor] Fontsize:16 context:@"病情描述" isCenter:NO];
    _placeholderLabel = [[UILabel alloc] init];
    _placeholderLabel.text = @"";
    [self setThelabel:_placeholderLabel color:KHColorFromRGB(0x999999) Fontsize:15 context:@"请对病情进行详细描述" isCenter:NO];
    _describeTextView = [[UITextView alloc] init];
    _describeTextView.backgroundColor = [UIColor whiteColor];
    _describeTextView.delegate = self;
    _describeTextView.font = [UIFont systemFontOfSize:15];
    // 语音部分
    _voicelable = [[UILabel alloc] init];
    [self setThelabel:_voicelable color:[UIColor blackColor] Fontsize:16 context:@"用户语音" isCenter:NO];
    _voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_voiceBtn setImage:[UIImage imageNamed:@"user_voice"] forState:UIControlStateNormal];
    [_voiceBtn addTarget:self action:@selector(playRecordVoice:) forControlEvents:UIControlEventTouchUpInside];
    
    _consultLabel = [[UILabel alloc] init];
    //参考部分
    [self setThelabel:_consultLabel color:[UIColor blackColor] Fontsize:16 context:@"医生参考图片" isCenter:NO];
    
    _imageBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self setTheButton:_imageBtn1 color:[UIColor whiteColor] context:@"" image:[UIImage imageNamed:@"Reference_picture"]];
    [_imageBtn1 addTarget:self action:@selector(addSubPointOutView:) forControlEvents:UIControlEventTouchUpInside];
    _imageBtn1.tag = ButtonTag+1;
    
    _imageBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self setTheButton:_imageBtn2 color:[UIColor whiteColor] context:@"" image:[UIImage imageNamed:@"Reference_picture"]];
    [_imageBtn2 addTarget:self  action:@selector(addSubPointOutView:) forControlEvents:UIControlEventTouchUpInside];
    _imageBtn2.tag = ButtonTag+2;
    
    _imageBtn3 = [UIButton buttonWithType:UIButtonTypeCustom];
    [self setTheButton:_imageBtn3 color:[UIColor whiteColor] context:@"" image:[UIImage imageNamed:@"Reference_picture"]];
    [_imageBtn3 addTarget:self action:@selector(addSubPointOutView:) forControlEvents:UIControlEventTouchUpInside];
    _imageBtn3.tag = ButtonTag+3;
    
    _imageLabel1 = [[UILabel alloc] init];
    [self setThelabel:_imageLabel1 color:KHColorFromRGB(0x999999) Fontsize:14 context:@"发病部位" isCenter:YES];
    _imageLabel2 = [[UILabel alloc] init];
    [self setThelabel:_imageLabel2 color:KHColorFromRGB(0x999999) Fontsize:14 context:@"病例报告" isCenter:YES];
    _imageLabel3 = [[UILabel alloc] init];
    [self setThelabel:_imageLabel3 color:KHColorFromRGB(0x999999) Fontsize:14 context:@"X光片" isCenter:YES];
    
    _postVoiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self setTheButton:_postVoiceBtn color:KHColorFromRGB(0x4bb92c) context:@"按住发语音" image:[UIImage new]];
}
// 添加视图 和约束
- (void)addSubViewAndMasony {
    [self.view addSubview:self.mainScrollView];
    [self.mainScrollView addSubview:_describeLabel];
    [self.mainScrollView addSubview:_describeTextView];
    [self.mainScrollView addSubview:_placeholderLabel];
    [self.mainScrollView addSubview:_voicelable];
    [self.mainScrollView addSubview:_voiceBtn];
    [self.mainScrollView addSubview:_consultLabel];
    [self.mainScrollView addSubview:_imageBtn1];
    [self.mainScrollView addSubview:_imageBtn2];
    [self.mainScrollView addSubview:_imageBtn3];
    [self.mainScrollView addSubview:_imageLabel1];
    [self.mainScrollView addSubview:_imageLabel2];
    [self.mainScrollView addSubview:_imageLabel3];
    [self.view addSubview:_postVoiceBtn];
    [_describeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mainScrollView).offset(14*ysIZE);
        make.width.equalTo(self.mainScrollView).multipliedBy(0.5);
        make.left.equalTo(self.mainScrollView).offset(10*xsIZE);
        make.height.mas_offset(16*ysIZE);
    }];
    [_describeTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mainScrollView);
        make.top.equalTo(_describeLabel.mas_bottom).offset(10.5*ysIZE);
        make.width.equalTo(self.mainScrollView);
        make.height.mas_offset(180*ysIZE);
    }];
    [_placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_describeTextView).offset(5*xsIZE);
        make.top.equalTo(_describeTextView).offset(8*ysIZE);
        make.height.offset(15*ysIZE);
        make.width.offset(160*xsIZE);
    }];
    [_voicelable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_describeTextView.mas_bottom).offset(14*ysIZE);
        make.left.width.height.equalTo(_describeLabel);
    }];
    [_voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_voicelable.mas_bottom).offset(14*ysIZE);
        make.left.equalTo(_voicelable);
        make.height.offset(40*ysIZE);
        make.width.offset(205*xsIZE);
    }];
    [_consultLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_voiceBtn.mas_bottom).offset(35*ysIZE);
        make.left.width.height.equalTo(_describeLabel);
    }];
    [_imageBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_consultLabel.mas_bottom).offset(15*ysIZE);
        make.left.equalTo(self.view).offset(20*xsIZE);
        make.width.offset(80*xsIZE);
        make.height.offset(80*xsIZE);
    }];
    [_imageBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.equalTo(_imageBtn1);
        make.left.equalTo(_imageBtn1.mas_right).offset(20*xsIZE);
    }];
    [_imageBtn3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.equalTo(_imageBtn2);
        make.right.equalTo(self.view.mas_right).offset(-20*xsIZE);
    }];
    [_imageLabel1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_imageBtn1.mas_bottom).offset(15*ysIZE);
        make.centerX.equalTo(_imageBtn1);
        make.height.offset(14*xsIZE);
        make.width.equalTo(_imageBtn1).multipliedBy(0.8);
    }];
    [_imageLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.equalTo(_imageLabel1);
        make.centerX.equalTo(_imageBtn2);
    }];
    [_imageLabel3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.height.equalTo(_imageLabel2);
        make.centerX.equalTo(_imageBtn3);
    }];
    [_postVoiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view);
        make.width.equalTo(self.mainScrollView);
        make.height.offset(50*xsIZE);
        make.left.equalTo(self.view);
        
    }];
}

// 三个图片按钮的方法
- (void)addSubPointOutView:(UIButton *)sender {
    _selectIndex = sender.tag - ButtonTag; // 记录要选照片的button
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.pointOutView];
   
}
// 改变照片的方法
- (void)imagePickWithIndex:(NSInteger)cellIndex image:(UIImage *)image {
    if (cellIndex == 1) {
        [_imageBtn1 setBackgroundImage:image forState:UIControlStateNormal];
        [self imageDictPutUpWithString:@"part" WithImage:image];
        return;
    }else if (cellIndex == 2) {
        [_imageBtn2 setBackgroundImage:image forState:UIControlStateNormal];
        [self imageDictPutUpWithString:@"report" WithImage:image];
        return;
    }else if (cellIndex == 3) {
        [_imageBtn3 setBackgroundImage:image forState:UIControlStateNormal];
        [self imageDictPutUpWithString:@"xray" WithImage:image];
        return;
    }
}

//  选择照片来源
- (void)SelectCellIndexPath:(NSInteger)cellSection index:(NSInteger)cellIndex {
    [self.pointOutView removeFromSuperview];
    if (cellSection == 1) {
        [self.pointOutView removeFromSuperview];
        return;
    }else {
        
        if (cellIndex == 0) {
            // 判断是否登录
            if (!userInfo.uid || [userInfo.uid isEqualToString:@""]) {
                JTAlertView * alert = [[JTAlertView alloc] init];
                [alert showPleaseLoginFromviewController:self loginHandel:^{
                    LZLoginViewController * logVC = [[LZLoginViewController alloc] init];
                    JNavigationController * navVc = [[JNavigationController alloc] initWithRootViewController:logVC];
                    [self presentViewController:navVc animated:YES completion:nil];
                }];

            }
            
            LZSectedPicVC *selectedPic = [[LZSectedPicVC alloc] init];
            selectedPic.selectIndex = _selectIndex;
            [self.navigationController pushViewController:selectedPic animated:YES];
            
            
            return ;
        }else if (cellIndex == 1) {
            [JTTakeAlbumOrCamera takeAlbumWithViewcontroller:self withID:self];
            return;
        }else {
            [JTTakeAlbumOrCamera takeCameraWithViewcontroller:self withID:self];
            return;
        }
    }
}
// 选中照片后的回调;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self imagePickWithIndex:_selectIndex image:image];
    
}
// 设置上传图片的字典上传时根据key和
- (void)imageDictPutUpWithString:(NSString *)imageName WithImage:(UIImage *)pImage {
    [_imageDict setObject:pImage forKey:imageName];
}
// 处理  上传图片和 录音 返回服务器返回的url
- (void)UploadImageAndVoice {
    ESWeak(self, cWeakSelf);
    NSMutableDictionary * upDict = [[NSMutableDictionary alloc] init];
    NSMutableDictionary * voiceDict =[@{} mutableCopy];
    // 先将 图片装入字典
    for (NSString * key in _imageDict.allKeys) {
        [upDict setObject:_imageDict[key] forKey:key];
    }
    // 如果有语音 将语音装入字典
    if (_voice) {
        NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        plistPath = [plistPath stringByAppendingString:@"/data.aac"];
        NSData *idata = [NSData dataWithContentsOfFile:plistPath];
        [upDict setObject:idata forKey:@"voice"];
        [voiceDict setObject:_postTimeNumber forKey:@"voice_time"];
    }
    
    [YJProgressHUD showProgress:@"上传中..." inView:self.view];
    [BaseRequest zRequestWithFile:TestURL paramars:voiceDict paramarsSite:@"Index/upProblem" fileDict:upDict progressBlock:^(NSProgress *uploadProgress) {
        
    } successBlock:^(id content) {
        _rightBarBtn.userInteractionEnabled = YES; // 开启交互
        NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1) {
            [YJProgressHUD showMessage:@"上传成功" inView:self.view];
            [cWeakSelf jumpdetailVCWith:[dict[@"list"] mutableCopy]];
        }else {
            [YJProgressHUD showMessage:@"上传失败" inView:self.view];
        }
        
    } failure:^(NSError * error) {
        [YJProgressHUD showError:@"上传失败，请重试" inview:cWeakSelf.view];
    }];
}
// 跳转到详情界面
- (void)jumpdetailVCWith:(NSMutableDictionary *)dict {
    if (_describeTextView.text && ![_describeTextView.text isEqualToString:@""]) {
            NSString * string = [_describeTextView.text stringByReplacingOccurrencesOfString:@"\"" withString:@"”" ];
        [dict setObject:string forKey:@"title"];
    }
    for ( NSString * key in dict.allKeys) {
        [_jumpDict setObject:dict[key] forKey:key];
    }
    ZPublishDetailsViewController * ZPDVC = [[ZPublishDetailsViewController alloc] init];
    ZPDVC.infoDict = _jumpDict;
    [self.navigationController pushViewController:ZPDVC animated:YES];
}

/**
 * 播放录音
 */
- (void)playRecordVoice:(UIButton *)sender {
    //在播放的时候 再次点击就暂停当前的录音的播放
     [[SPVoiceManager defaultManager]playingMusicUrl:_recordUrl];
//    if ([self.avPlay isPlaying]) {
//        [self.avPlay pause];
//        return;
//    }else{
//        AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:_recordUrl error:nil];
//        if(!_timer) {
//            return;
//        }
//        self.avPlay = player;
//        [self.avPlay play];
//        
//        //根据是否插入耳机  决定是否是扬声器或者耳机播放
//        NSError *setCategoryError = nil;
//        if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
//                                              withOptions:AVAudioSessionCategoryOptionMixWithOthers
//                                                    error:&setCategoryError]) {
//        }
//        //通知录音和播放
//        UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
//        AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
//        //播放时长
//        AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:_recordUrl options:nil];
//        CMTime audioDuration = audioAsset.duration;
//        float audioDurationSeconds =CMTimeGetSeconds(audioDuration);
//        NSLog(@"%f",audioDurationSeconds);
//    }
}

/**
 * 录音设置
 */
- (void)setUpRecord{
    
    //录音设置
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    
    NSString *name = [NSString stringWithFormat:@"/data.aac"];
    //沙盒路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:name];
    //
    urlPlay = path;
    //
    NSURL *url = [NSURL fileURLWithPath:path];
    _recordUrl = url;
    
    NSError *error;
    //初始化
    recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量检测
    recorder.meteringEnabled = YES;
    recorder.delegate = self;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    //音量平均值
    [recorder averagePowerForChannel:100];
    
    //进行一些界面的设置
    [self showVoice];
    
}

/**
 * 显示话筒和音节大小
 */
- (void)showVoice{
    self.recordDuraTimeLabel = [[UILabel alloc] init];
    [self.view addSubview:self.recordDuraTimeLabel];
    [self.recordDuraTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.equalTo(_voiceBtn.mas_height);
        make.centerY.equalTo(_voiceBtn);
        make.right.equalTo(_voiceBtn);
    }];
    _callView = [UIView new];
    _callView.hidden = YES;
    [self.view addSubview:_callView];
    [_callView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.view.mas_centerY);
    }];
    _callView.layer.cornerRadius = 10;
    _callView.clipsToBounds = YES;
    _callView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
    
    _label = [[UILabel alloc] initWithFrame:CGRectZero];
    _label.translatesAutoresizingMaskIntoConstraints = NO;
    _label.textAlignment = NSTextAlignmentCenter;
    _label.font = [UIFont systemFontOfSize:12];
    _label.backgroundColor = [UIColor clearColor];
    _label.text = @"松开手指，停止录音";
    _label.layer.cornerRadius = 5;
    _label.clipsToBounds = YES;
    _label.textColor = [UIColor whiteColor];
    [_callView addSubview:_label];
    
    _imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
    _imgView.translatesAutoresizingMaskIntoConstraints = NO;
    _imgView.image = [UIImage imageNamed:@"yuyin"];
    [_callView addSubview:_imgView];
    
    _maskView = [[UIView alloc] initWithFrame:CGRectZero];
    _maskView.translatesAutoresizingMaskIntoConstraints = NO;
    _maskView.backgroundColor = [UIColor whiteColor];
    [_callView addSubview:_maskView];
    
    _yinjieBtn = [[UIImageView alloc] initWithFrame:CGRectZero];
    _yinjieBtn.translatesAutoresizingMaskIntoConstraints = NO;
    [_callView addSubview:_yinjieBtn];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(_callView, _label, _imgView, _yinjieBtn, _maskView);
    
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_callView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:_callView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_callView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[_label]-|" options:0 metrics:nil views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_label]-|" options:0 metrics:nil views:views]];
    _centerX = [NSLayoutConstraint constraintWithItem:_imgView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_callView attribute:NSLayoutAttributeCenterX multiplier:1 constant:-20];
    [self.view addConstraint:_centerX];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_imgView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_callView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_yinjieBtn attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_imgView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_yinjieBtn attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:_imgView attribute:NSLayoutAttributeRight multiplier:1 constant:10]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[_imgView]-[_maskView]-|" options:0 metrics:nil views:views]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_maskView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_yinjieBtn attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    _maskH = [NSLayoutConstraint constraintWithItem:_maskView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:0];
    [self.view addConstraint:_maskH];

}
/**
 * 添加长按手势
 */
- (void)addLongPressGesture{
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressHandler:)];
    longPress.minimumPressDuration = 0.0;
    [_postVoiceBtn addGestureRecognizer:longPress];
}
/**
 * 长按手势的监听方法
 */
- (void)longPressHandler:(UILongPressGestureRecognizer *)press{
    NSError *error=nil;
    _audioSession = [AVAudioSession sharedInstance];
    
    [_audioSession setCategory:AVAudioSessionCategoryRecord error: &error]; //设置音频类别，这里表示当应用启动，停掉后台其他音频
    
    [_audioSession setActive:YES error: &error];//设置当前应用音频活跃性
    
    NSLog(@"__%s",__func__);
    //停止录音的播放
    //    [self.avPlay stop];
    [[SPVoiceManager defaultManager]stop];
    //停止录音的播放
    [self.avPlay stop];
    switch (press.state) {
        case UIGestureRecognizerStateBegan:
            //删除以前的录音
            [recorder deleteRecording];
            //显示音阶
            _callView.hidden = NO;
            //开始录音
            [recorder record];
            //定时器开始计时
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
            break;
        case UIGestureRecognizerStateEnded:
            //隐藏音阶
            _callView.hidden = YES;
            //释放定时器
            [_timer invalidate];
            //停止录音
            [recorder stop];
            //结束录音的操作
            [self endPress];
            break;
    }
}
/**
 * 开始长按手势后，图片开始动画
 */
- (void)changeImage{
    
    _time_number ++;
    //更新测量值
    [recorder updateMeters];
    
    [recorder updateMeters];//更新测量值
    float avg = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
    /**  根据声音分贝大小显示不同的音量图片  */
    if (avg > 0) {
        _yinjieBtn.image = [UIImage imageNamed:@"yinjie（1）"];
    }if (avg > 0.2) {
        _yinjieBtn.image = [UIImage imageNamed:@"yinjie（2）"];
    }if (avg > 0.4) {
        _yinjieBtn.image = [UIImage imageNamed:@"yinjie（3）"];
    }if (avg > 0.6) {
        _yinjieBtn.image = [UIImage imageNamed:@"yinjie（4）"];
    }if (avg > 0.8) {
        _yinjieBtn.image = [UIImage imageNamed:@"yinjie（5）"];
    }if (avg > 1.0) {
        _yinjieBtn.image = [UIImage imageNamed:@"yinjie（6）"];
    }
}
/**
 * 结束录音后的处理
 */
- (void)endPress{
    
    //录音时长计数归零
    _time_number = 0;
    /**  录音时长  */
    AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:_recordUrl options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds =CMTimeGetSeconds(audioDuration);
    
    
    
    if (audioDurationSeconds < 1.0f) {
        
        //提示至少要录音3s
        [YJProgressHUD showMessage:@"录音小于一秒无法进行上传" inView:self.view];
//        self.recordDuraTimeLabel.text = [NSString stringWithFormat:@""];
        _voice = NO;
    }else {
        
        self.recordDuraTimeLabel.text = [NSString stringWithFormat:@"%.f''",audioDurationSeconds];
        _voice = YES;
        _time_number =  audioDurationSeconds;
        _postTimeNumber = [NSString stringWithFormat:@"%.f",audioDurationSeconds]; ;
    }
    /** 录音时长  */
//     NSString * _voice_time = [NSString stringWithFormat:@"%.f",audioDurationSeconds];
}


// 监听textView的 输入
- (void)textViewDidChange:(UITextView *)textView {
    if ([textView.text length]== 0) {
        [_placeholderLabel setHidden:NO];
    } else {
        [_placeholderLabel setHidden:YES];
    }
}
// 设置按钮的方法
- (void)setTheButton:(UIButton *)sender color:(UIColor *)Pcolor context:(NSString *)title image:(UIImage *)image {
    [sender setBackgroundImage:image forState:UIControlStateNormal];
    [sender setBackgroundColor:Pcolor];
    [sender setTitle:title forState:UIControlStateNormal];
    
}
// 设置label
- (void)setThelabel:(UILabel *)sender color:(UIColor *)Pcolor Fontsize:(NSInteger)size context:(NSString *)text isCenter:(BOOL)center{
    sender.text = text;
    sender.textColor = Pcolor;
    sender.font = [UIFont systemFontOfSize:size];
    sender.textAlignment = center?  NSTextAlignmentCenter: NSTextAlignmentLeft;
    
}

// lazy
- (UIScrollView *)mainScrollView {
    if (_mainScrollView) {
       return _mainScrollView;
    }
    _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _mainScrollView.contentSize = CGSizeMake(SCREEN_Width,1.1*SCREEN_Height);
    return _mainScrollView;
}
- (PointOutView *)pointOutView {
    if (_pointOutView) {
        return _pointOutView;
    }
    _pointOutView = [[PointOutView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_Width, SCREEN_Height)];
    _pointOutView.pointDeleGate  = self;
    return _pointOutView;
}

-(ZUnpaidView *)unpaidView {
    if (_unpaidView) {
        return _unpaidView;
    }
    _unpaidView = [[ZUnpaidView alloc] init];
    _unpaidView.frame = CGRectMake(0, 0, SCREEN_Width, SCREEN_Height);
    _unpaidView.GoPayBtnBolck = ^() {
        NSLog(@"我再跳转");
    };

    return _unpaidView;
}


@end
